package errcode

import (
	"fmt"
)

// Error ...
type Error struct {
	code    int      `json:"code"`
	msg     string   `json:"msg"`
	details []string `json:"details"`
}

var codes = map[int]string{}

// NewError ...
func NewError(code int, msg string) *Error {
	if _, has := codes[code]; has {
		panic(fmt.Sprintf("错误码 %d 已存在，请更换", code))
	}

	codes[code] = msg
	return &Error{code: code, msg: msg}
}

// Error ...
func (e *Error) Error() string {
	if e.details != nil {
		return fmt.Sprintf("错误码: %d ,错误信息: %s,详情：%s", e.Code(), e.Msg(), e.details)
	} else {
		return fmt.Sprintf("错误码: %d ,错误信息: %s", e.Code(), e.Msg())
	}

}

// Code ...
func (e *Error) Code() int {
	return e.code
}

// Msg ...
func (e *Error) Msg() string {
	return e.msg
}

// Details ...
func (e *Error) Details() []string {
	return e.details
}

// WithDetails ...
func (e *Error) WithDetails(details ...string) *Error {
	e.details = []string{}
	for _, d := range details {
		e.details = append(e.details, d)
	}
	return e
}
